package Day019_Junit单元测试_NIO.ZuoYe;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author zhangyan
 * @date 2020/5/12 18:36
 */
public class Test2 {
    public static void main(String[] args) throws Exception{

        //创建RandomAccessFile 只读模式
        RandomAccessFile raf1 = new RandomAccessFile("Demo02\\aaa\\e.txt","r");
        //创建RandomAccessFile 读写模式
        RandomAccessFile raf2 = new RandomAccessFile("Demo02\\aaa\\eCopy.txt","rw");

        //获取FileChannel通道对象
        FileChannel fc1 = raf1.getChannel();
        FileChannel fc2 = raf2.getChannel();

        //直接把硬盘的文件映射到内存中(MappedByteBuffer)
        MappedByteBuffer mbb1 = fc1.map(FileChannel.MapMode.READ_ONLY, 0, fc1.size());
        MappedByteBuffer mbb2 = fc2.map(FileChannel.MapMode.READ_WRITE, 0, fc1.size());

        //循环读写数据
        for (long i = 0; i < fc1.size(); i++) {
            //mbb1读取到的字节数据,存储在mbb2中
            mbb2.put(mbb1.get());
        }

        //关闭资源
        fc2.close();
        fc1.close();
        raf2.close();
        raf1.close();
    }
}
